package top.houry.im.client.netty;

import cn.hutool.core.lang.Singleton;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import top.houry.im.client.controller.ImClientLoginUiController;
import top.houry.im.client.factory.ImClientThreadFactory;
import top.houry.im.client.listener.ImClientNettyProcessorListener;
import top.houry.im.client.proto.ImMessage;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ImClientNetty {

    private final EventLoopGroup clientEventLoopGroup = new NioEventLoopGroup(1, new ImClientThreadFactory("im-client"));

    private static volatile ImClientNetty instance;
    private ImClientNetty() {
    }
    public static ImClientNetty getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new ImClientNetty();
                }
            }
        }
        return instance;
    }


    public void startImClient() {
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(clientEventLoopGroup).channel(NioSocketChannel.class).handler(new ImClientNettyInitializer());
            ChannelFuture channelFuture = bootstrap.connect("localhost",8899).addListener(new ImClientNettyProcessorListener("连接服务器")).sync();
            ImClientLoginUiController.getInstance().showNetworkTip(false);
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e ) {

            ImClientLoginUiController.getInstance().showNetworkTip(true);

            this.startImClient();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        }
    }

    public void stopImClient() {
        clientEventLoopGroup.shutdownGracefully();
    }




}